<template>
  <div style="padding: 20px; display: flex">
    <img src="@/img/signin.png" alt="" style="margin-top: 10%" />
    <el-card style="width: 40%; margin: auto; margin-top: 15%">
      <el-form :model="user" :rules="rules" ref="user">
        <el-form-item label="用户名" prop="name">
          <el-input placeholder="请输入用户名" v-model="user.name" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="user.password"
            clearable
            show-password
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: center">
        <el-button type="text" @click="signin('user')">登录</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: "",
        password: "",
      },
      rules: {
        name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    signin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            (this.user.name === "guoyaohang" &&
              this.user.password === "0503") ||
            (this.user.name === "admin" && this.user.password === "admin")
          ) {
            this.$message.success("登录成功");
            //登录成功之后 username存入cookie用于保持登录状态以及确定当前用户
            this.setCookie("username", this.user.name, 1);
            this.$store.username = this.user.name;
            //跳转首页
            this.$router.push("/");
          } else {
            this.$message.error("账号或者密码错误");
          }
        }
      });
    },
    setCookie(cname, cvalue, exdays) {
      var d = new Date();
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
      var expires = "expires=" + d.toGMTString();
      document.cookie = cname + "=" + cvalue + "; " + expires;
    },
  },
};
</script>

<style>
</style>